<template>
  <div class="tp">
    <Header/>

    <Content>
      <div class="cp">
        <div class="card">
          <BasicForm @register="registerFilter" @submit="onSearch">
          </BasicForm>

          <a-tabs v-model:activeKey="state.search.type" type="line">
            <a-tab-pane v-for="o in repaymentStatus" :key="o.value" :tab="o.label">
              <BasicTable @register="state[o.value].registerTable" :resizeHeightOffset="44">
                <template #action="{ record }">
                  <TableAction
                      :divider="true"
                      :actions="[
                        o.value===0&& {
                        color: 'success',
                        label: '还款',
                        onClick: () => onRepayment(record),
                      },

                      {
                        color: 'success',
                        label: '详情',
                        onClick: () => onDetail(record),
                      }
                    ].filter(o=>!!o)"
                  />
                </template>
              </BasicTable>
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>
    </Content>

    <RepaymentDialog @register="registerRepayment" @complete="onComplete"/>
    <DebtLogDetail @register="registerDebtLog" @complete="onSearch"/>
  </div>
</template>

<script setup>
import {defineOptions, h, nextTick, onMounted, reactive, watch, provide } from 'vue';

import {useRouter} from 'vue-router';

import {BasicTable, TableAction, useTable} from '@/components/Table';

import DebtLogDetail from './debt-log-detail.vue';
import RepaymentDialog from './repayment-dialog.vue';
import Header from '@/widget/header.vue';
import Content from '@/widget/content.vue';
import {PAGE} from '@/api/http';
import {repaymentStatus,} from '@/api/ds';

import {BasicForm, useForm} from '@/components/Form/index';
import {useModal} from "@/components/Modal";
import {useDrawer} from "@/components/Drawer";

defineOptions({name: 'DebtList'});

provide('onSearch', { onSearch });

const [registerDebtLog, {openDrawer: debtLogDrawer}] = useDrawer();
const [registerRepayment, {openModal: repaymentModal}] = useModal();

const router = useRouter();

const [registerFilter, filter] = useForm({
  baseColProps: {style: {paddingRight: '12px'}},
  actionColOptions: {span: 16},
  submitOnReset: true,
  schemas: [
    {
      field: 'query',
      component: 'Input',
      componentProps: {
        placeholder: '输入客户姓名/手机号进行搜索',
      },
      colProps: {span: 8},
    },
  ],
});

const [registerTable0, table0] = useTable({
  api: PAGE('/membership/debtsList'),
  immediate: false,
  beforeFetch: (arg) => Object.assign(getSearchArg(arg), {repaymentStatus: 0}),
  columns: [
    {
      title: '客户信息',
      dataIndex: 'memberCode',
      ellipsis: false,
      customRender: ({record}) =>
          h('span', {innerHTML: `${record.realName}&nbsp;${record.mobile}`},),
    },

    {
      title: '累计欠款金额',
      dataIndex: 'debtAmountSum',
      ellipsis: false,
    },
    {
      title: '累计还款金额',
      dataIndex: 'repaymentAmountSum',
      ellipsis: false,
    },
    {
      title: '剩余欠款金额',
      dataIndex: 'debtAmount',
      ellipsis: false,
      sorter: true,
    },
    {
      title: '最近还款时间',
      dataIndex: 'repaymentTime',
      ellipsis: false,
    },
  ],
  useSearchForm: false,
  showTableSetting: false,
  bordered: true,
  showIndexColumn: false,
  rowKey: 'memberCode',
  actionColumn: {
    title: '操作',
    align: 'center',
    width: 120,
    dataIndex: 'action',
    fixed: 'right',
    slots: {customRender: 'action'},
  },
});

const [registerTable1, table1] = useTable({
  api: PAGE('/membership/debtsList'),
  immediate: false,
  beforeFetch: (arg) => Object.assign(getSearchArg(arg), {repaymentStatus: 1}),
  columns: [
    {
      title: '客户信息',
      dataIndex: 'memberCode',
      ellipsis: false,
      customRender: ({record}) =>
          h('span', {innerHTML: `${record.realName}&nbsp;${record.mobile}`},),
    },

    {
      title: '累计欠款金额',
      dataIndex: 'debtAmountSum',
      ellipsis: false,
    },
    {
      title: '累计还款金额',
      dataIndex: 'repaymentAmountSum',
      ellipsis: false,
    },
    {
      title: '剩余欠款金额',
      dataIndex: 'debtAmount',
      ellipsis: false,
      sorter: true,
    },
    {
      title: '最近还款时间',
      dataIndex: 'repaymentTime',
      ellipsis: false,
    },
  ],
  useSearchForm: false,
  showTableSetting: false,
  bordered: true,
  showIndexColumn: false,
  rowKey: 'memberCode',
  actionColumn: {
    title: '操作',
    align: 'center',
    width: 120,
    dataIndex: 'action',
    fixed: 'right',
    slots: {customRender: 'action'},
  },
});

const state = reactive({
  search: {
    type: 0
  },
  0: {
    registerTable: registerTable0,
    table: table0,
  },
  1: {
    registerTable: registerTable1,
    table: table1,
  },
  tempRecord: {}
});

function getSearchArg(arg) {
  const {field, order} = arg;
  const rank = order === 'descend' ? 'desc' : 'asc';

  if (field === 'debtAmount') {
    arg.orderByValue = `mmd.debt_amount ${rank}`;
  }

  const data = filter.getFieldsValue();
  return Object.assign(arg, data);
}

onMounted(() => {
  onSearch();
});

watch(
    () => state.search.type,
    () => nextTick(onSearch),
);

function onDetail(record) {
  debtLogDrawer(true, {record});
  sessionStorage.setItem('debtAmount', record.debtAmount);
}

function onRepayment(record) {
  const {memberCode, debtAmount} = record;
  repaymentModal(true, {memberCode, debtAmount});
  state.tempRecord = record
}

async function onSearch() {
  const {type} = state.search,
      target = state[type];

  target.table.reload();
  target.table.redoHeight();
}

async function onComplete(e) {
  onSearch(); 
  onDetail({...state.tempRecord, debtAmount: state.tempRecord.debtAmount - e })
}
</script>
<style lang="less" scoped>
.card {
  padding: 16px;
}

:deep(.ant-tabs-nav) {
  margin: 0 8px 8px;
}
</style>
